/*
 * Graph.cpp
 *
 *  Created on: Sep 18, 2012
 *      Author: pedro
 */

#include "Graph.h"

/**
 * constroi o grafo a partir de um tamanho
 */
Graph::Graph(int size) {
	if (size > 0)
	{
		matrix = new int *[size];

		for (int i = 0; i < size; ++i)
			matrix[i] = new int[size];

		this->size = size;
	}

}

/**
 * constroi o grafo a partir de um arquivo de entrada
 */
Graph::Graph(string input) {
	ifstream file;

	file.open(input.c_str());

	if (file.is_open())
	{
		int size;
		file >> size;

		matrix = new int *[size];

		for (int i = 0; i < size; ++i)
			matrix[i] = new int[size];

		this->size = size;

		for (int i = 0; i < size; ++i)
		{
			for (int j = 0; j < size; ++j)
			{
				file >> matrix[i][j];
			}
		}
	} else
	{
		cout << "Porblema na abertura do arquivo" << input << endl;
		exit(1);
	}

}

Graph::Graph(Graph &g) {

	this->size = g.size;

	matrix = new int *[size];

	for (int i = 0; i < size; ++i)
		matrix[i] = new int[size];

	for (int i = 0; i < size; ++i)
	{
		for (int j = 0; j < size; ++j)
		{
			matrix[i][j] = g(i, j);
		}
	}
}

Graph::Graph(const Graph &g) {
	this->size = g.size;

	matrix = new int *[size];

	for (int i = 0; i < size; ++i)
		matrix[i] = new int[size];

	for (int i = 0; i < size; ++i)
	{
		for (int j = 0; j < size; ++j)
		{
			matrix[i][j] = g.matrix[i][j];
		}
	}

}

/**
 * desaloca o grafo
 */
Graph::~Graph() {

	for (int i = 0; i < size; ++i)
		delete[] (matrix[i]);

	delete[] matrix;

	// TODO Auto-generated destructor stub
}

/**
 * retorna o tamanho do grafo
 */
int Graph::getSize() {
	return size;
}

int ** Graph::getMatrix() {
	return matrix;
}

/**
 * gera um grafo fortemente conexo aleatorio
 */
void Graph::generate() {
	srand (time(NULL));

double	prob, parameter;

	for(int i = 0; i < size; i++)
	{
		for(int j = i; j < size; j++)
		{
			if(i != j)
			{
				matrix[i][j] = rand()%MAX_WEIGHT + 1;
				matrix[j][i] = matrix[i][j];
			}
			else
			matrix[i][j] = DASH;
		}
	}
}

/**
 * salva o grafo em um arquivo
 */
bool Graph::save(string output) {
	ofstream file;

	file.open(output.c_str());

	if (file.is_open())
	{
		file << size << endl;

		for (int i = 0; i < size; ++i)
		{
			for (int j = 0; j < size; ++j)
			{
				file << matrix[i][j] << " ";
			}
			file << endl;
		}

		return true;
	}

	return false;
}

void Graph::print() {

	for (int i = 0; i < size; ++i)
	{
		for (int j = 0; j < size; ++j)
		{
			cout << matrix[i][j] << " ";
		}
		cout << endl;
	}

}

void Graph::send(int dest) {
	for (int i = 0; i < size; ++i)
	{
		COMM_WORLD.Send(matrix[i], size, INT, dest, GRAPH_TAG);
	}
}

void Graph::receive(int source) {
	for (int i = 0; i < size; ++i)
	{
		COMM_WORLD.Recv(matrix[i], size, INT, source, GRAPH_TAG);
	}

}

